package com.tongfusoft.utils;

import java.util.HashMap;
import java.util.Map;

public class MapUtils {

    /**
     * 
    *根据key，获取Map中对应值
    *
    * @param    
    * @return T
    * @throws
     */
	public static <T> T get(Map map, Object key) {
		return (T) MapUtils.get(map, key, null);
	}

	/**
	 * 
	*根据key，获取Map中对应值,如果没有对应的key，则返回默认值
	*
	* @param    
	* @return T
	* @throws
	 */
	public static <T> T get(Map map, Object key, T def) {
		if (map.containsKey(key)) {
			if (def == null)
				return (T) map.get(key);
			if (map.get(key).getClass().isAssignableFrom(def.getClass()))
				return (T) map.get(key);
		}
		return def;
	}

	/**
	 * 
	*返回Map工厂
	*
	* @param    
	* @return MapFactory
	* @throws
	 */
	public static MapFactory factory() {
		return new MapFactory(new HashMap());
	}

	public static class MapFactory {

		private HashMap<String, Object> hashMap;

		private MapFactory(HashMap<String, Object> hashMap) {
			this.hashMap = hashMap;
		}

		public HashMap<String, Object> create() {
			return this.hashMap;
		}

		public MapFactory put(String key, Object value) {
			this.hashMap.put(key, value);
			return this;
		}
	}

	public static Map newMap(Object... args) {
		Map map = new HashMap();
		int i = 0;
		while (i < args.length) {
			map.put(args[i++], args[i++]);
		}
		return map;
	}

	public static void copyMap(Map desc, Map orgi) {
		for (Object entry : orgi.entrySet()) {
			desc.put(((Map.Entry) entry).getKey(),
					((Map.Entry) entry).getValue());
		}

	}

	public static void main(String[] args) {
		try {
			Map map = new HashMap();
			map.put("string", "string");
			map.put("int", 1);
			map.put("long", 1l);
			map.put("boolean", true);
			System.out.println(get(map, "string", "default string"));
			System.out.println(get(map, "int", 2));
			System.out.println(get(map, "long", 2l));
			boolean bool = get(map, "test", false);
			Boolean b = get(map, "boolean2", new Boolean(false));
			System.out.println(b);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
